package by.grsu.matrenichev.page.testing;

import java.util.List;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;

import by.grsu.matrenichev.dao.TestingDao;
import by.grsu.matrenichev.entity.Testing;
import by.grsu.matrenichev.page.BasePage;

@SuppressWarnings("serial")
public class ListTestingPage extends BasePage {

	@SpringBean
	private TestingDao testingDao;

	public ListTestingPage() {
		super();
		// retrieve all objects
		final List<Testing> testings = testingDao.findAll();

		// add "list" component and provide list of items which should be
		// rendered
		add(new ListView<Testing>("testing", testings) {

			@Override
			protected void populateItem(final ListItem<Testing> item) {
				final Testing testing = item.getModelObject();
				// add "labels" to display each property of the item
				item.add(new Label("testname", testing.getTestname()));
				item.add(new Label("subject", testing.getSubject()));
				item.add(new Label("question1", testing.getQuestion1()));
				item.add(new Label("question2", testing.getQuestion2()));
				item.add(new Label("question3", testing.getQuestion3()));
				item.add(new Label("mark",String.valueOf(testing.getMark())));

				// add link which will forward to the "edit" page
				item.add(new Link<Testing>("editlink", new Model<Testing>(testing)) {
					@Override
					public void onClick() {
						setResponsePage(new EditTestingPage(testing));
					}
				});

				// add "link" which removes item from database and reload the
				// page
				item.add(new Link<Testing>("deletelink", new Model<Testing>(testing)) {
					@Override
					public void onClick() {
						testingDao.delete(getModelObject().getId());
						setResponsePage(ListTestingPage.class);
					}
				});
			}

		});

		// redirect to the "edit" page using "empty" model to create new item as
		// result
		add(new Link<Testing>("createLink", new Model<Testing>(new Testing())) {
			@Override
			public void onClick() {
				setResponsePage(new EditTestingPage(getModelObject()));
			}
		});

	}
}
